package com.hjh.usb.accessory.communication

import androidx.core.app.PendingIntentCompat.send
import com.elvishew.xlog.XLog
import java.io.*
import java.util.concurrent.*
import java.util.concurrent.atomic.AtomicBoolean

class AOACommunicatorSingleThread(
    private val inputStreamProvider: () -> InputStream?,
    private val outputStreamProvider: () -> OutputStream?
) {
    companion object {
        private const val BUFFER_SIZE = 64 * 1024
        private const val ACK_TIMEOUT_MS = 60_000L
    }

    private val running = AtomicBoolean(false)
    private val sending = AtomicBoolean(false)

    private var inputStream: InputStream? = null
    private var outputStream: OutputStream? = null

    fun start() {
        inputStream = inputStreamProvider()
        outputStream = outputStreamProvider()
        running.set(true)
        val buffer = ByteArray(BUFFER_SIZE)

        while (running.get()) {
            try {
                val len = inputStream?.read(buffer) ?: break
                if (len > 0) {
                    val data = buffer.copyOf(len)
                    if (PacketUtils.isAckPacket(data) && sending.get()) {
                        send()
                        break
                    }
                }
            } catch (e: IOException) {
                XLog.e("接收线程异常: ${e.message}")
                UsbFlow.updateConnectionState(ConnectionState.Error("接收错误: ${e.message}"))
            }
        }
    }

    fun send() {
        if (!running.get()) return
        if (UsbFlow.usbConnState.value !is ConnectionState.Connected) return

        try {
            val fileSize = 500 * 1024L
            var chunkIndex = 0
            val buffer = ByteArray(BUFFER_SIZE) { 0x02 }

            while (running.get()) {
                val bytesRead = buffer.size // 模拟读取
                if (bytesRead <= 0) break

                val packet = PacketUtils.buildDataPacket(
                    fileSize = fileSize,
                    chunkIndex = chunkIndex++,
                    data = buffer,
                    length = bytesRead
                )

                sending.set(true)

                try {
                    outputStream?.write(packet)
                    outputStream?.flush()
                    XLog.i("第${chunkIndex}包")
                } catch (e: IOException) {
                    e.printStackTrace()
                    XLog.e("发送异常: ${e.message}")
                    UsbFlow.updateConnectionState(ConnectionState.Error("发送错误: ${e.message}"))
                    return
                }

                sending.set(false)
            }

            XLog.tag("Accessory Send").i("文件发送完成")
        } catch (e: Exception) {
            XLog.e("文件发送异常: ${e.message}")
            UsbFlow.updateConnectionState(ConnectionState.Error("文件发送异常: ${e.message}"))
        }
    }

    fun sendFile(file: File): Boolean {
        if (!running.get()) return false
        if (UsbFlow.usbConnState.value !is ConnectionState.Connected) return false

        try {
            val fileSize = file.length()
            var chunkIndex = 0
            val buffer = ByteArray(BUFFER_SIZE) { 0x02 }


            while (true) {
                val bytesRead = buffer.size // 模拟读取
                if (bytesRead <= 0) break

                val packet = PacketUtils.buildDataPacket(
                    fileSize = fileSize,
                    chunkIndex = chunkIndex++,
                    data = buffer,
                    length = bytesRead
                )

                sending.set(true)

                try {
                    outputStream?.write(packet)
                    outputStream?.flush()
                    XLog.i("第${chunkIndex}包")
                } catch (e: IOException) {
                    e.printStackTrace()
                    XLog.e("发送异常: ${e.message}")
                    UsbFlow.updateConnectionState(ConnectionState.Error("发送错误: ${e.message}"))
                    return false
                }

                sending.set(false)
            }

            XLog.tag("Accessory Send").i("文件发送完成")
        } catch (e: Exception) {
            XLog.e("文件发送异常: ${e.message}")
            UsbFlow.updateConnectionState(ConnectionState.Error("文件发送异常: ${e.message}"))
        }
        return true
    }


    fun stop() {
        running.set(false)

        try {
            inputStream?.close()
            outputStream?.close()
        } catch (_: Exception) {
        }

        XLog.tag("Accessory").i("线程池通信已停止，资源释放完毕")
    }
}
